<?php

namespace common\behaviors;

use bedezign\yii2\audit\Audit;
use bedezign\yii2\audit\AuditTrailBehavior;
use bedezign\yii2\audit\models\AuditTrail;
use yii\db\Expression;

class ModelAuditBehavior extends AuditTrailBehavior
{

    /**
     * Save the audit trails for a create or update action
     *
     * @param $action
     * @param $newAttributes
     * @param $oldAttributes
     * @param $entry_id
     * @param $user_id
     * @param $model
     * @param $model_id
     * @param $created
     * @throws \yii\db\Exception
     */
    protected function saveAuditTrail($action, $newAttributes, $oldAttributes, $entry_id, $user_id, $model, $model_id, $created)
    {
        $rows = [];
        foreach ($newAttributes as $field => $new)
        {
            $old = isset($oldAttributes[$field]) ? $oldAttributes[$field] : '';
            if ($new instanceof Expression)
            {
                $rows[] = [$entry_id, $user_id, $old, $new, $action, $model, $model_id, $field, $created];
            }
            elseif ($new != $old)
            {
                $rows[] = [$entry_id, $user_id, $old, $new, $action, $model, $model_id, $field, $created];
            }
        }
        if ( ! empty($rows))
        {
            $columns = [
                'entry_id',
                'user_id',
                'old_value',
                'new_value',
                'action',
                'model',
                'model_id',
                'field',
                'created'
            ];
            /** @var Audit $audit */
            $audit = Audit::getInstance();
            $audit->getDb()->createCommand()->batchInsert(AuditTrail::tableName(), $columns, $rows)->execute();
        }
    }
}
